<template>
  <div
    v-loading="loading"
    style="display: flex; flex-direction: column; flex: 1"
    element-loading-text="加载中..."
  >
    <div class="header flex-justify-between">
      <div class="btns flex-align-center">
        <button class="btn btn-bg2 mr5" @click="addData">
          <span class="iconfont icon-xinjian mr5"></span>添加字段</button
        >
        <el-dropdown trigger="click">
          <el-button
            class="btn btn-bg5 btn-all"
            :style="selecttion.length == 0 ? 'border: 1px solid #ccc;color:#999' : ''"
            :disabled="selecttion.length == 0"
          >
            <img :src="batch" class="iconfont mr5" alt="" sizes="16" srcset="" />批量操作
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon> <CircleCheck /> </el-icon>批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon> <Warning /> </el-icon>批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon> <Delete /> </el-icon>批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search flex-align-center">
        <el-select
          v-model="category"
          class="input-select"
          placeholder="请选择字段类型"
          clearable
          filterable
          @change="getList"
        >
          <el-option label="多行文本" value="1" />
          <el-option label="单选" value="2" />
          <el-option label="多选" value="3" />
          <el-option label="附件" value="4" />
          <el-option label="手机号" value="5" />
        </el-select>
        <el-input
          v-model.trim="name"
          clearable
          placeholder="关键词搜索"
          class="input-width mr5"
          @keyup.enter="getList"
          @clear="getList"
        />
        <button class="btn btn-bg1" @click="getList">
          <el-icon class="mr5"> <Search /> </el-icon>搜索
        </button>
      </div>
    </div>
    <div class="table-list">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        height="100%"
        style="position: absolute"
        @selection-change="handleChange"
      >
        <el-table-column show-overflow-tooltip type="selection" width="40" />
        <el-table-column show-overflow-tooltip prop="name" label="字段名称" min-width="200" />
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <el-tag v-if="!scope.row.status" type="success">启用</el-tag>
            <el-tag v-if="scope.row.status" type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="category" label="字段类型" width="100">
          <template #default="scope">
            <span>
              {{
                scope.row.category == 1
                  ? '多行文本'
                  : scope.row.category == 2
                  ? '单选'
                  : scope.row.category == 3
                  ? '多选'
                  : scope.row.category == 4
                  ? '附件'
                  : '手机号'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="content" label="字段内容" width="250" />
        <el-table-column show-overflow-tooltip prop="tip" label="提示信息" width="100">
          <template #default="scope">
            <span> {{ scope.row.tip }} </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <div class="flex-center">
              <button class="btn-table bgColor2" @click="editData(scope.row)">详细</button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  字段弹窗 -->
    <el-dialog
      v-model="addDialog"
      width="350px"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      class="add-dialog2"
      top="12vh"
    >
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ fieldDialogTitle }}</h3>
        </div>
      </template>
      <div v-loading="fieldLoading" element-loading-text="加载中...">
        <div class="form-text">
          <el-form ref="formRef" label-width="80" :rules="rules" :model="ruleForm">
            <el-form-item label="字段名称" class="form-item" prop="name">
              <el-input
                v-model.trim="ruleForm.name"
                class="item-input"
                clearable
                placeholder="请输入名称"
              />
            </el-form-item>
            <el-form-item label="字段类型" class="form-item">
              <el-select
                v-model="fieldType"
                placeholder="请选择"
                filterable
                class="item-input"
                clearable
              >
                <el-option
                  v-for="(item, index) in options1"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
              /></el-select>
            </el-form-item>
            <el-form-item label="是否必填" class="form-item">
              <el-radio-group v-model="radio2" class="el-group">
                <el-radio :value="false">
                  <span class="bg_text">选填</span>
                </el-radio>
                <el-radio :value="true">
                  <span class="bg_text">可填</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="字段状态" class="form-item">
              <el-radio-group v-model="radio1" class="el-group">
                <el-radio :value="false">
                  <span class="bg_text">启用</span>
                </el-radio>
                <el-radio :value="true">
                  <span class="bg_text">禁用</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="提示信息" class="form-item">
              <el-input
                v-model.trim="tip"
                class="item-input"
                clearable
                placeholder="请输入提示信息"
              />
            </el-form-item>
            <div v-if="fieldType == 2 || fieldType == 3" class="field-text flex-justify-between">
              <span>字段内容</span>
              <span class="addText" @click="addText">+ 新增</span>
            </div>
            <div v-if="fieldType == 2 || fieldType == 3" class="list">
              <el-form ref="fieldFormRef" :model="fieldForm" :rules="rules">
                <div v-for="(item, index) in fieldForm.items" :key="index">
                  <el-form-item
                    class="text-item flex-justify-between"
                    :prop="`items[${index}][val]`"
                    :rules="rules.text"
                  >
                    <div class="num">{{ index + 1 }}</div>
                    <div>
                      <el-input
                        v-model.trim="item.val"
                        class="text-input"
                        clearable
                        placeholder="请输入字段内容"
                      />
                    </div>
                    <div class="delete" @click="handleDele(index, item)">删除</div>
                  </el-form-item>
                </div>
              </el-form>
            </div>
            <el-form-item v-if="fieldType == 4" label="上传附件" class="form-item">
              <el-input
                v-model.trim="annex"
                class="item-input"
                clearable
                placeholder="请输入类型"
              />
            </el-form-item>
            <el-form-item v-if="fieldType == 4" label="最大尺寸" class="form-item" prop="maxSize">
              <el-input
                v-model.trim="ruleForm.maxSize"
                class="item-input"
                clearable
                placeholder="请输入尺寸"
                @input="limitNum(ruleForm.maxSize, 100)"
                @change="ruleForm.maxSize ? '' : (ruleForm.maxSize = 1)"
              />
            </el-form-item>
            <el-form-item v-if="fieldType == 4" label="上传数量" class="form-item" prop="uploadNum">
              <el-input
                v-model.trim="ruleForm.uploadNum"
                class="item-input"
                clearable
                placeholder="请输入数量"
                @input="limitNum(ruleForm.uploadNum, 10)"
                @change="ruleForm.uploadNum ? '' : (ruleForm.uploadNum = 1)"
              />
            </el-form-item>
          </el-form>
        </div>
        <div :class="fieldDialogTitle == '编辑字段' ? 'flex-justify-between' : 'btns'">
          <el-button
            v-show="fieldDialogTitle == '编辑字段'"
            color="#f56c6c"
            class="btn_delete"
            @click="changeStatus(4)"
            >删除</el-button
          >
          <div class="right">
            <el-button class="btn_cancel" @click="addDialog = false"> 取消 </el-button>
            <el-button color="#007cff" class="btn_save" @click="saveAddField(formRef, fieldFormRef)"
              >保存</el-button
            >
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import batch from '@/assets/image/batch.png'
  import { ref, reactive, markRaw } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { Search, Delete, Warning } from '@element-plus/icons-vue'
  import { fieldList, fieldSave, fieldDisable, fieldDelete, fieldInfo } from '@/api/goodsSet'
  import { phone } from '@/utils/validate'

  const loading = ref(false)
  const name = ref('') // 名称
  const category = ref('') // 字段类型
  const tableData = ref([]) // 列表数据
  const tableDom = ref() // 列表dom
  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目
  const addDialog = ref(false)

  const fieldDialogTitle = ref('')
  const fieldLoading = ref(false)

  const options1 = [
    {
      value: 1,
      label: '多行文本',
    },
    {
      value: 2,
      label: '单选',
    },
    {
      value: 3,
      label: '多选',
    },
    {
      value: 4,
      label: '附件',
    },
    {
      value: 5,
      label: '手机号',
    },
  ]

  // 表单数据 1-单位  2-类型  3-规格  4-字段
  const ruleForm = reactive({
    maxSize: 1,
    uploadNum: 1,
    name: '',
    phone: '', // 手机号
  })

  const fieldForm = reactive({
    items: [
      {
        val: '',
      },
    ],
    itemIDs: [], // 删除的字段内容ID集合
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
    maxSize: [
      { required: false, message: '请输入最大尺寸', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    uploadNum: [
      { required: false, message: '请输入上传数量', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
    text: [{ required: true, message: '请输入字段内容', trigger: 'blur' }],
    phone: [
      { required: false, message: '请输入手机号', trigger: 'blur' },
      { validator: phone(ruleForm.phone), trigger: 'blur' },
    ],
  })
  const limitNum = (val, n) => {
    if (val > n) {
      val = n
    } else if (val == 0 && val != '') {
      val = 1
    }
    if (n == 100) {
      ruleForm.maxSize = val
    } else {
      ruleForm.uploadNum = val
    }
  }
  const formRef = ref<FormInstance>()
  const fieldFormRef = ref<FormInstance>()

  // 字段内容
  const fieldID = ref('')
  const fieldType = ref(1) // 字段类型
  const radio1 = ref(false) // 状态
  const radio2 = ref(false) // 字段选填
  const annex = ref('.jpg,.png,.gif') // 附件
  const maxSize = ref(1) // 最大尺寸
  const uploadNum = ref(1) // 上传数量
  const tip = ref('') // 提示信息

  // 获取列表选中的数据
  const selecttion = ref([])
  const handleChange = (val) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    const data = {
      category: category.value,
      name: name.value,
      limit: pagination.value.size,
      page: pagination.value.current,
    }
    await fieldList(data).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 新增字段内容
  const addText = () => {
    const tmp = {
      val: '',
    }
    fieldForm.items.push(tmp)
  }

  // 删除字段内容
  const handleDele = (index, obj) => {
    fieldForm.items.splice(index, 1)
    fieldForm.itemIDs.push(obj.id)
  }

  // 添加字段
  const addData = () => {
    fieldDialogTitle.value = '添加字段'
    ruleForm.name = ''
    fieldType.value = 1
    radio1.value = false
    radio2.value = false
    annex.value = '.jpg,.png,.gif'
    maxSize.value = 1
    uploadNum.value = 1
    tip.value = ''
    fieldForm.items = [
      {
        val: '',
      },
    ]
    addDialog.value = true
  }

  // 编辑字段
  const editData = (obj) => {
    fieldLoading.value = true
    fieldDialogTitle.value = '编辑字段'
    fieldID.value = obj.id
    ruleForm.name = obj.name
    fieldType.value = obj.category
    radio1.value = obj.status
    radio2.value = obj.required
    maxSize.value = obj.maxSize
    uploadNum.value = obj.uploadNum
    addDialog.value = true
    fieldInfo(fieldID.value).then((res) => {
      fieldForm.items = res.data.data.row.contentVos
      fieldLoading.value = false
    })
  }

  // 封装保存字段的数据
  const saveField = (title, text, method) => {
    const data = {
      category: fieldType.value,
      contentIds: [],
      contentVos: [],
      maxSize: maxSize.value,
      name: ruleForm.name,
      required: radio2.value,
      status: radio1.value,
      tip: tip.value,
      uploadNum: uploadNum.value,
    }
    const data2 = {
      id: fieldID.value,
      category: fieldType.value,
      contentIds: fieldForm.itemIDs,
      contentVos: fieldForm.items,
      maxSize: maxSize.value,
      name: ruleForm.name,
      required: radio2.value,
      status: radio1.value,
      tip: tip.value,
      uploadNum: uploadNum.value,
    }
    if (fieldType.value == 2 || fieldType.value == 3) {
      let tmp = []
      fieldForm.items.forEach((item) => {
        tmp.push({ val: item.val })
      })
      data.contentVos = tmp
    }
    if (title == text) {
      method(data).then((res) => {
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'warning',
          duration: 2000,
        })
        if (res.data.success == true) {
          addDialog.value = false
          getList()
        }
      })
    } else {
      method(data2).then((res) => {
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'warning',
          duration: 2000,
        })
        if (res.data.success == true) {
          addDialog.value = false
          getList()
        }
      })
    }
  }

  // 保存字段
  const saveAddField = (formEl: FormInstance | undefined, formEl2: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        if (fieldType.value == 2 || fieldType.value == 3) {
          formEl2.validate((val) => {
            if (val) {
              saveField(fieldDialogTitle.value, '添加字段', fieldSave)
            }
          })
        } else {
          saveField(fieldDialogTitle.value, '添加字段', fieldSave)
        }
      } else {
        return
      }
    })
  }

  // 修改状态方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的字段`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的字段?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'warning',
            duration: 2000,
          })
          if (res.data.success) {
            selecttion.value = []
            tableDom.value.clearSelection()
            getList()
          }
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'warning',
            duration: 2000,
          })
          if (res.data.success) {
            selecttion.value = []
            tableDom.value.clearSelection()
            getList()
            if (dialog != '') {
              addDialog.value = false
            }
          }
        })
      }
    })
  }

  // 批量启用/禁用/删除
  const changeStatus = (n) => {
    if (n == 1) {
      changeMethod('启用', fieldDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', fieldDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', fieldDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', fieldDelete, [fieldID.value], 3, addDialog)
    }
  }

  defineExpose({ getList })
</script>

<style scoped lang="scss"></style>
